import type { FormRule } from 'tdesign-vue-next';
import { ref } from 'vue';

export class formGroup {
  /** 初始数据 */
  public INITIAL_DATA = ref<Record<string, any>>({});
  /** 名字 */
  public Name = ref<Array<string>>([]);
  /** 是否显示 */
  public Visible = ref<Record<string, boolean>>({});
  /** 标题 */
  public Title = ref<Record<string, string>>({});
  /** 尺寸 */
  public Size = ref<Record<string, string>>({});
  /** 格式验证 */
  public Rules = ref<Record<string, Record<string, FormRule[]>>>({});
  /** 数据 */
  public Data = ref<Record<string, any>>({});
  /** 接口 */
  public Post = ref<Record<string, (data: any) => Promise<boolean>>>({});
  /** 布局 */
  public Layout = ref<Record<string, any>>({});

  /** 添加表单对话框
   * @param name 调用的名字
   * @param title 显示的标题
   * @param INITIAL_DATA 初始数据
   * @param post 请求
   * @param rules 格式验证
   * @param size 宽度
   */
  public add<T = { data: Record<string, any> }>(
    /** 名字 */
    name: string,
    /** 标题 */
    title: string,
    /** 初始化信息 */
    INITIAL_DATA: Record<string, any> | T extends { data: Record<string, any> }
      ? { data: Record<string, any> }
      : Record<string, any>,
    /** 请求 */
    post: (data: T) => Promise<any>,
    /** 格式验证 */
    rules?: Record<string, FormRule[]>,
    /** 对话框尺寸 */
    size?: string,
    /** 布局 */
    layout?: 'vertical' | 'inline',
  ) {
    this.Name.value.push(name);
    this.Visible.value[name] = false;
    this.Title.value[name] = title;
    this.Data.value[name] = {};
    this.INITIAL_DATA.value[name] = 'data' in INITIAL_DATA ? INITIAL_DATA.data : INITIAL_DATA;
    this.Post.value[name] = post;
    this.Rules.value[name] = rules || <any>[];
    this.Size.value[name] = size || '';
    this.Layout.value[name] = layout || 'vertical';
  }

  /** 显示表单对话框 */
  show(/** 名字 */ name: string, /** 数据 */ data?: any, /** 标题 */ title?: string) {
    const nameIndex = this.Name.value.findIndex((item) => {
      return name == item;
    });
    // 名称不存在
    if (nameIndex == -1) return;
    // 是否需要设置数据
    if (data && Object.keys(data).length != 0) {
      this.Data.value[name] = { ...data };
    } else {
      this.Data.value[name] = { ...this.INITIAL_DATA.value[name] };
    }
    // 如果需要设置标题
    if (title) {
      this.Title.value[name] = title;
    }
    // 显示输入框
    this.Visible.value[name] = true;
  }
  /**
   * 隐藏表单对话框
   * @param name 表单名称
   */
  public hide(name: string) {
    const index = this.Name.value.findIndex((item) => item === name);
    if (index !== -1) {
      this.Visible.value[name] = false;
    }
  }
}
